package com.googlecode.cswish.security.type;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.cswish.security.Context;


/**
 * @author Jerry.Feng Date: Nov 8, 2007 2:04:16 PM
 * @version $id: $
 */
public class RuleSetOr implements Calculation {

	protected boolean alwaysTrue;
	
	protected List<Calculation> expressList = new ArrayList<Calculation>();
	
	public static final RuleSetOr TRUE = new RuleSetOr() {
		@Override
		public boolean executeBoolean(Context context) {
			return true;
		}
	};
	
	@Override
	public String execute(Context context) {
		//return String.valueOf(executeBoolean(context));
		String result = "";
		for (Iterator<Calculation> iter = expressList.iterator(); iter.hasNext();) {
			Calculation expression = iter.next();
			
			result += expression.execute(context);
		}
		return result;
	}

	@Override
	public boolean executeBoolean(Context context) {
		if (alwaysTrue) {
			return true;
		}
		
		for (Iterator<Calculation> iter = expressList.iterator(); iter.hasNext();) {
			Calculation expression = iter.next();
			
			boolean ret = true;
			ret &= expression.executeBoolean(context);
				
			if (ret) {
				return ret;
			}
		}
		return false;
	}
	
	public RuleSetOr addRule(Calculation expression) {
		if (alwaysTrue) {
			// do nothing
		} else if (expression == null || expression.executeBoolean(null)) {
			alwaysTrue = true;
		} else {
			expressList.add(expression);
		}
		return this;
	}
}